package com.android.music.prolyric.songmanager;




import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

import android.media.MediaMetadataRetriever;




public class ListFolderMusic {
	private static ArrayList<FolderMusic> listFoderMP3 =new  ArrayList<FolderMusic>();
	private static final String 	HOME_PATH = new String("sdcard/");
	private static final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();

	
	
	public static void listFile(String path)
	{
		File f = new File(path); 
		
			
			if(f.isDirectory()&&f.list()!=null) 
			{
				ArrayList<HashMap<String, String>> listMusicFile = new  ArrayList<HashMap<String,String>>();
				
				if(f.list(new FileExtensionFilter()).length>0) 
				{
					String[] files = f.list(new FileExtensionFilter());
					for(String s : files)
					{
						HashMap<String, String> hm = new HashMap<String, String>();
						
						hm.put("songpath", f.getPath()+"/"+s);
					
					
						metaRetriever.setDataSource(f.getPath()+"/"+s);
						String artist = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
						String title = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
						String duration = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
						String display = s.substring(0, s.length()-4);
						
						hm.put("artist", artist == null ? "<unknow>":artist);
						hm.put("title", title == null ? display:title);
						hm.put("duration", duration);
						
						listMusicFile.add(hm); 
					}
					FolderMusic fm = new FolderMusic();
					fm.setPath(f.getPath());
					fm.setListMusicFile(listMusicFile);
					listFoderMP3.add(fm);
				}
				
				String [] listFile = f.list();
				for(String lf : listFile)
				{
					File fs = new File(f.getPath()+"/"+lf);
					if(fs.isDirectory())
						listFile(f.getPath()+"/"+lf);
				}
			}
			
	
				

	}
	
	public static  ArrayList<FolderMusic> getFolderMusic()
	{
		listFile(HOME_PATH);
		return listFoderMP3;
	}
	
	
	
	static class FileExtensionFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(".mp3") || name.endsWith(".MP3"));
		}
	}

}
